(function() {
  var wxapi = "//res.wx.qq.com/open/js/jweixin-1.0.0.js", qqapi = "//open.mobile.qq.com/sdk/qqapi.js?_bid=152", qzapi = "//qzonestyle.gtimg.cn/qzone/phone/m/v4/widget/mobile/jsbridge.js?_bid=339";
  var require;

  var reportbehaviourUrl = "//useraction.96189.com"; //用户行为汇报地址 useraction.96189.com  //210.51.168.119:2016

  function _require(url, onload) {
    var doc = document;
    var head = doc.head || (doc.getElementsByTagName("head")[0] || doc.documentElement);
    var node = doc.createElement("script");
    node.onload = onload;
    node.onerror = function() {
    };
    node.async = true;
    node.src = url[0];
    head.appendChild(node);
  }
  function _initWX(data) {
    if (!data.WXconfig) {
      return;
    }
    // 二次分享替换图片为固定logo
    data.pic = "http://yztv-vod.homecdn.com/2562aac2bebd4e75a0dadb7c60e1e8dc.png";
    require([wxapi], function(wx) {
      if (!wx.config) {
        wx = window.wx;
      }
      var conf = data.WXconfig;
      wx.config({
        debug: false,
        appId: conf.appId,
        timestamp: conf.timestamp,
        nonceStr: conf.nonceStr,
        signature: conf.signature,
        jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"]
      });
      wx.error(function(res) {
      });
      wx.ready(function () {
        var config = {
          title: data.title,
          desc: data.summary,
          link: data.url,
          imgUrl: data.pic,
          type: "",
          dataUrl: "",
          success: function () {
            data.callback && data.callback();
           shareUrlReport(reportbehaviourUrl,data.reportdata,"share");
          },
          cancel: function () {

          }
        };
        wx.onMenuShareAppMessage(config);
        wx.onMenuShareQQ(config);
        wx.onMenuShareQZone(config);
        if (conf.swapTitleInWX) {
          wx.onMenuShareTimeline({
            title: data.summary,
            desc: data.title,
            link: data.url,
            imgUrl: data.pic,
            type: "",
            dataUrl: "",
            success: function () {
              data.callback && data.callback();
            },
            cancel: function () {
            }
          });
        } else {
          wx.onMenuShareTimeline(config);
        }
      });
    });
  }
  function _initQQ(data) {
	// 二次分享替换图片为固定logo
	data.pic = "http://yztv-vod.homecdn.com/2562aac2bebd4e75a0dadb7c60e1e8dc.png";

    var info = {title:data.title, desc:data.summary, share_url:data.url, image_url:data.pic,reportdata:data.reportdata};

    function doQQShare() {
      try {
        if (data.callback) {
          window.mqq.ui.setOnShareHandler(function (type) {
            if (type == 3 && (data.swapTitle || data.WXconfig && data.WXconfig.swapTitleInWX)) {
              info.title = data.summary;
            } else {
              info.title = data.title;
            }
            info.share_type = type;
            info.back = true;
            window.mqq.ui.shareMessage(info, function (result) {
              if (result.retCode === 0) {
                data.callback && data.callback.call(this, result);

                shareUrlReport(reportbehaviourUrl,info.reportdata,"share");
              }
            });
          });
        } else {
          window.mqq.data.setShareInfo(info);
        }
      } catch (e) {
      }
    }
    if (window.mqq) {
      doQQShare();
    } else {
      require([qqapi], function() {
        doQQShare();
      });
    }
  }

  function shareUrlReport(apiurl,reportbehaviourData,actiontype){
    if (!reportbehaviourData && !actiontype)
      return;

    if (window.yfH5ShareApp.Env.isWeixin()) {
      reportbehaviourData.sharetype = "weixin";
    } else if (window.yfH5ShareApp.Env.isQQ()) {
      reportbehaviourData.sharetype = "cqq";
    } else if (window.yfH5ShareApp.Env.isWeiBo()) {
      reportbehaviourData.sharetype="sina";
    }else{
      reportbehaviourData.sharetype="web browser";
    }

    var actioncontextbehaviour = {
      version: "1.1",
      data: reportbehaviourData,
    }
    var infobehaviours = {
      actiontype: actiontype,
      createtime: new Date().Format("yyyyMMddhhmmss"),
      actioncontext: actioncontextbehaviour
    }

    if (window.yfH5ShareApp.Env.isAndroid()) {
      infobehaviours.client = "android";
    } else if (window.yfH5ShareApp.Env.isIOS()) {
      infobehaviours.client = "ios";
    } else {
      infobehaviours.client = "h5";
    }
    var arrybehaviours = [infobehaviours];
    var reportdata = {
      sourcetype: "h5",
      behaviours: arrybehaviours
    }

    var apiUrl=apiurl+"/webapi/userbehaviour/report"
    var postdata = JSON.stringify(reportdata);

    $.ajax({
      url: apiUrl,
      type: 'POST',
      data: postdata,
      dataType: 'json',
      contentType: 'application/json',
      error: function(data) {
        console.error("汇报失败:"+ actiontype);
      },
      success: function(data) {
        console.log("汇报成功:"+ actiontype);
      }
    });
  }

  function _initQZ(data) {
    function doQZShare() {
      if (QZAppExternal && QZAppExternal.setShare) {
        var imageArr = [], titleArr = [], summaryArr = [], shareURLArr = [];
        // 二次分享替换图片为固定logo
        data.pic = "http://yztv-vod.homecdn.com/2562aac2bebd4e75a0dadb7c60e1e8dc.png";
        for (var i = 0;i < 5;i++) {
          imageArr.push(data.pic);
          shareURLArr.push(data.url);
          if (i === 4 && (data.swapTitle || data.WXconfig && data.WXconfig.swapTitleInWX)) {
            titleArr.push(data.summary);
            summaryArr.push(data.title);
          } else {
            titleArr.push(data.title);
            summaryArr.push(data.summary);
          }
        }
        QZAppExternal.setShare(function(data) {
        }, {"type":"share", "image":imageArr, "title":titleArr, "summary":summaryArr, "shareURL":shareURLArr});
      }
    }
    if (window.QZAppExternal) {
      doQZShare();
    } else {
      require([qzapi], function() {
        doQZShare();
      });
    }
  }
  function init(opts) {
    var ua = navigator.userAgent;
    var isWX = ua.match(/MicroMessenger\/([\d\.]+)/), isQQ = ua.match(/QQ\/([\d\.]+)/), isQZ = ua.indexOf("Qzone/") !== -1;
    isWX && _initWX(opts);
    isQQ && _initQQ(opts);
    isQZ && _initQZ(opts);
  }
  if (typeof define === "function" && (define.cmd || define.amd)) {
    if (define.cmd) {
      require = seajs.use;
    } else {
      if (define.amd) {
        require = window.require;
      }
    }
    define(function() {
      return init;
    });
  } else {
    require = _require;
    window.setShareInfo = init;
  }

  window.initShareConfig = function (sharetitle, sharedesc, sharepic, shareurl, reportdata, secondShareUrl) {
    try {
      /*
       var timestamp;
       var noncestr; //随机串
       var signature; //签名
       */
      if (!window.yfH5CShareConfig)
        window.yfH5CShareConfig = {
          timestamp: null,
          noncestr: null,
          signature: null,
          appid: "wxad55f090d8fcd385"
        };
      var conUrl = window.location.href;
      var par = {
        url: conUrl
      };
      $.ajax({
        type: 'POST',
        //contentType: "application/json;charset=utf-8",
        // url:"http://admin.96189.com/urc/external/share",
        url: secondShareUrl ? secondShareUrl : "//admin.96189.com/urc/external/share",
        data: par,
        dataType: 'json',
        async: false,
        success: function (data) {
          if (!data.state || !data.result || data.state.rc != 0) {
            console.error("后台返回的参数不正确");
            return;
          }
          window.yfH5CShareConfig.timestamp = data.result.timestamp;
          window.yfH5CShareConfig.noncestr = data.result.noncestr;
          window.yfH5CShareConfig.signature = data.result.signature;
        }
      });
      console.log('timestamp=' + window.yfH5CShareConfig.timestamp + ',noncestr=' + window.yfH5CShareConfig.noncestr + ',signature=' + window.yfH5CShareConfig.signature);

      setShareInfo({
        title: sharetitle,
        summary: sharedesc,
        pic: sharepic,
        url: shareurl,
        reportdata: reportdata,
        WXconfig: {
          swapTitleInWX: false,
          appId: yfH5CShareConfig.appid,
          timestamp: yfH5CShareConfig.timestamp,
          nonceStr: yfH5CShareConfig.noncestr,
          signature: yfH5CShareConfig.signature
        }
      });
    } catch (e) {
      console.error(e);
    }

  }
})();
